from .models import *
import glob
import threading


'''
表关系：
Remark:
        remark   id1:书名作者都匹配，id2,原网站没有作者

Contrast:验证库存
        book_name,book_author

Book:小说网站的所有书目
        name,author,url

Site:网站信息
    name,site

BookUrl:Book和Contrast匹配到的url。
        book = Fk(Contrast),site = Fk(Site),
        remark = Fk(Remark),
        url

'''
class WorkContrast:


    site_obj = Site.objects.get(pk =1)
    remark_1 = Remark.objects.get(pk = 1)
    remark_2 = Remark.objects.get(pk = 2 )
    queue = iter(range(1,102066))

    #传入一个contrast的pk值，和Book中的信息做对比，
    #如果匹配则记录到BookUrl中，分两种情况，一种是完全匹配，
    #一种是书名匹配因为BookUrl中没有作者一栏
    def contrast(self,contrast_pk):

        try:

            con_obj = Contrast.objects.get(pk = contrast_pk)
            book_name = con_obj.book_name
            book_author = con_obj.book_author
            
        except Contrast.DoesNotExist:

            return 'Contrast表中没有pk值为"{contrast_pk}"的数据'

        try:
            
            book_obj = Book.objects.get(name = book_name)

            
        except Book.DoesNotExist:

            return '{}书名没匹配到'.format(book_name)#验证失败
        
        except Book.MultipleObjectsReturned:

            chongfu.objects.create(chongfu = contrast_pk)

            return '{}找到多个'.format(book_name)
            
        
        else:

            if book_obj.author == '':

                BookUrl.objects.create(book = con_obj,
                                       site = self.site_obj,
                                       remark = self.remark_2,
                                       url = book_obj.url, 
                                       )
                return '{}书名匹配到了但是Book中没有提供作者'.format(book_name)

            elif book_obj.author == book_author:

                BookUrl.objects.create(book = con_obj,
                                       site = self.site_obj,
                                       remark = self.remark_1,
                                       url = book_obj.url,                                      
                                       )
                return '{}完美匹配'.format(book_name)

            elif book_obj.author != book_author:

                return '{}书名一样但是作者不同'.format(book_name)

                

    def runing(self):

        while True:

            try:

                i = next(self.queue)

            except StopIteration:

                print('工作完成，线程退出 ')

                break

            else:

            

                print('现在匹配Contrast表中Pk值为{}的数据'\
                      .format(i))

                print(self.contrast(i))

    def my_thread(self):

        pool = []
        for i in range(10):
            pool.append(threading.Thread(target = self.runing))
        for i in pool:
            i.start()
        for i in pool:
            i.join()

        print('大结局')

                

            
            

        

        




























    
